<template>
    <el-drawer
      :modelValue="modelValue"
      :direction="direction"
      :with-header="withHeader"
      :size="size"
      :close-on-click-modal="closeOnClickModal"
      :destroy-on-close="destroyOnClose"
      :append-to-body="appendToBody"
      :z-index="zIndex"
      @update:modelValue="updateDrawer">
      <template #default>
        <div class="drawer-container" >
          <el-icon size="20" @click="close" class="close-icon"><Close /></el-icon>
          <div class="left-container">
            <div class="aside">
              <div class="aside-top">
                <img class="avatar" :src="data.avatar" alt="头像"/>
                <label>{{username}}</label>
              </div>
              <div class="tag-container">
                <template v-if="tagList.length > 0">
                  <el-tag type="primary" v-for="tag in tagList" :key="tag.id" closable @close="handleClose(tag)">{{tag.name}}</el-tag>
                  <el-icon class="m-icon" @click="showPanel"><Plus /></el-icon>
                </template>
                <el-button v-else :icon="Plus" size="small" plain @click="showPanel">顾客标签</el-button>
                <div class="my-panel" v-if="isShow">
                  <el-cascader
                    ref="casValue"
                    placeholder="请选择标签"
                    :options="options"
                    :props="panelProps"
                    :show-all-levels="false"
                    @change="chooseTag"
                    @remove-tag="handleRemoveTag"
                    filterable />
                </div>
              </div>

            </div>
            <div class="switch">
              <div @click="handleTab(1)" :class="['switch-item',tabActive === 1 ? 'tabActive':'']">名片</div>
              <div @click="handleTab(2)" :class="['switch-item',tabActive === 2 ? 'tabActive':'']">访问</div>
            </div>
            <div class="sec-box">
              <ul>
                <li class="m-li" v-for="field in fieldList" :key="field.id">
                  <label>{{field.title}}</label>
                  <el-input v-if="field.show" ref="inputRef" size="default" v-model="field.content" @change="handleChange(field)" @blur="field.show = false"/>
                  <div class="value" v-else @click="handleEditField(field)">
                    <span class="pad-r">{{field.content}}</span>
                    <el-icon class="icon"><EditPen /></el-icon>
                  </div>
                </li>
              </ul>
            </div>
            <div class="sec-box">
              <ul>
                <li class="m-li">
                  <label>创建时间</label>
                  <div class="value">{{data.create_time}}</div>
                </li>
                <li class="m-li">
                  <label>更新时间</label>
                  <div class="value">{{data.create_time}}</div>
                </li>
                <li class="m-li">
                  <label>上一次对话时间</label>
                  <div class="value">{{data.create_time}}</div>
                </li>
                <li class="m-li">
                  <label>广告主ID</label>
                  <div class="value">{{data.create_time}}</div>
                </li>
                <li class="m-li">
                  <label>计划ID</label>
                  <div class="value">{{data.create_time}}</div>
                </li>
                <li class="m-li">
                  <label>创意ID</label>
                  <div class="value">{{data.create_time}}</div>
                </li>
                <li class="m-li">
                  <label>企业微信</label>
                  <div class="value">{{data.create_time}}</div>
                </li>
                <li class="m-li">
                  <label>对话渠道</label>
                  <div class="value">{{data.create_time}}</div>
                </li>
              </ul>
            </div>
          </div>
          <div class="right-container">
            <div class="tabs">
              <div @click="handleSwitch(tab)" class="tabs-item" :class="activeId === tab.id ? 'active' : ''" v-for="(tab,index) in tabsList" :key="tab.id">{{tab.name}}</div>
            </div>
          </div>
        </div>
      </template>
    </el-drawer>
</template>

<script setup lang="ts">
  import { Close,Plus,EditPen } from '@element-plus/icons-vue'
  import {FieldService} from '@/api/customer/fieldApi'
  import {TagService} from '@/api/customer/tagApi'
  import {CustomerService} from '@/api/customer/customerApi'
  import avatar from '@imgs/user/avatar.png'
  import type {DrawerProps} from './Drawer'

  const props = withDefaults(defineProps<DrawerProps>(),{
      modelValue:false,
      appendToBody:true,
      lockScroll:true,
      closeOnClickModal:false,
      openDelay:10,
      closeDelay:10,
      destroyOnClose:false,
      modal:true,
      direction:'rtl',
      showClose:true,
      size:'60%',
      withHeader:false,
      zIndex:999,
      data:{
        nickname:'张三',
        avatar:avatar,
      }
  })

  const username = ref('')
  const inputRef = ref(null)
  const tabActive = ref(1)
  const activeId = ref(4)
  const isShow = ref(false)
  const query = reactive({
    page: 1,
    limit: 10,
    customer_id:props.data.id
  })

  const tabsList = reactive([
    // {id:1,name:'浏览记录'},
    // {id:2,name:'行为事件'},
    // {id:3,name:'对话记录'},
    {id:4,name:'操作记录'},
  ])
  const tagList = ref([])

  const casValue = ref()
  const options = ref([])
  const panelProps = {
    multiple: true,
    value:'id',
    label:'name',
  }

  // 显示添加顾客标签
  function showPanel() {
    isShow.value = true
  }

  const handleTab = (val:number) => {
    tabActive.value = val
  }

  const handleSwitch = (item:any) => {
    activeId.value = item.id
  }

  // 选择标签
  const chooseTag = async (item:any) => {
    const nodes = casValue.value.getCheckedNodes(true)
    // nodeInfo.forEach((node:any) => {
    //   tagList.value.push(node.data)
    // })
   async function addTag() {
      for(let val of nodes){
        if(val.isChecked) {
          continue;
        }
        val.isChecked = true
        console.log('val',val)
        const params = {customer_id:props.data.id,tag_id:val.value}
        await CustomerService.customerTagAdd(params)
      }
    }
    await addTag()
    await getCustomerTagList()
  }

  // 删除顾客标签
  const handleClose = async (tag:any)=> {
      await CustomerService.customerTagDelete({id:tag.id})
      await getCustomerTagList()
  }

  // 移除tag是触发
  const handleRemoveTag = (item:any) => {
    console.log('移除是触发',item)
  }

  const handleEditField = (item:any) => {
    fieldList.value.map(field=>{ field.show = false })
    item.show = true
    nextTick(() => {
      inputRef.value[0].focus()
    })
  }
  const fieldList = ref([])

  initData()
  async function initData() {
    await getCustomerDetail()
    await getFieldList()
    await getCustomerFieldValueList()
    await getCustomerTagList()
    getTagTypeList()
    await getPageOperateLog()
  }

  // 获取操作记录
  async function getPageOperateLog() {
    const res = await CustomerService.getOperateLog(toRaw(query))
    console.log(res)
  }

  // 获取标签列表和分类
  function getTagTypeList() {
    TagService.getTypeList().then(res => {
      res.data.forEach(async (item:any)=>{
        const {data} = await TagService.getTagList({type_id:item.id})
        if(data.length > 0) {
          item.children = data.map((tag:any) => {
            tag.isCheckbox = true
            return tag
          })
        }
      })
      options.value = res.data
      console.log('options',options.value)
    })
  }

  // 获取属性字段列表
  async function getFieldList() {
    const res = await FieldService.getFieldList()
    fieldList.value = res.data
  }

  // 获取顾客属性值列表
  async function getCustomerFieldValueList() {
    const res = await CustomerService.getCustomerFieldList({customer_id:props.data.id})
    fieldList.value.forEach((field:any)=>{
      field.show = false
      res.data.forEach((item:any)=>{
        if(item.name === 'name') {
          username.value = item.content
        }
        if(field.name === item.name) {
          field.content = item.content
          field.t_id = item.id
        }
      })
    })
  }

  // 获取顾客详情
  async function getCustomerDetail() {
    const res = await CustomerService.getCustomerDetail({customer_id:props.data.id})
    console.log(res)
  }

  // 获取顾客标签列表
  async function getCustomerTagList() {
    const res = await CustomerService.getCustomerTagList({customer_id:props.data.id})
    tagList.value = res.data
  }

  // 添加顾客属性
  async function operationCustomerField(item:any) {
    const params = {customer_id:props.data.id,field_id:item.id,content:item.content}
    if(item.t_id && item.content) {
      await CustomerService.customerFieldUpdate({id:item.t_id,content:item.content})
    } else if(item.t_id && !item.content){
      await CustomerService.customerFieldDelete({id:item.t_id})
      delete item.t_id
    } else {
      await CustomerService.customerFieldAdd(params)
    }
  }
  // change事件
  const handleChange = async (item:any) => {
    console.log('change事件')
    console.log('item',item)
    await operationCustomerField(item)
    await getCustomerFieldValueList()
  }

  const emit = defineEmits(['update:modelValue','close'])

  const updateDrawer = (val?:boolean) => {
    emit('update:modelValue',false)
  }

  const close = ()=> {
    updateDrawer()
    emit('close')
  }
</script>
<style lang="scss" scoped>
  .drawer-container {
    height: 100%;
    display: flex;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 0;
    .close-icon {
      padding: 10px;
      position: absolute;
      right: 0;
      top: 8px;
      cursor: pointer;
    }
    .left-container {
      font-size: 14px;
      flex: 1;
      border-right: 1px solid rgba(4,15,66,.2);
      .aside {
        padding: 8px 15px 0;
        &-top {
          display: flex;
          align-items: center;
          margin-bottom: 8px;
        }
        .avatar {
          width: 48px;
          height: 48px;
          border-radius: 50%;
        }
        label {
          padding-left: 8px;
        }
        .my-panel {
          background: #fff;
        }
        .tag-container {
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          column-gap: 4px;
          row-gap: 4px;
          margin-bottom: 4px;
          position: relative;
        }
        .m-icon {
          color: var(--el-color-primary);
          border: 1px solid var(--el-color-primary);
        }
      }
      .switch {
        display: flex;
        padding: 12px;
        box-shadow: 0 3px 4px 0 #f4f6fb;
        &-item {
          flex: 1;
          cursor: pointer;
          text-align: center;
          line-height: 26px;
          color: rgba(4,15,66,.3);
        }
        .tabActive {
          color: var(--el-color-primary);
        }
      }
      .sec-box {
        padding: 10px 20px;
        font-size: 12px;
        border-bottom: 1px solid rgba(4,15,66,.2);
      }
      .m-li {
        margin: 15px 0;
        color: rgba(4,15,66,.9);
        display: flex;
        align-items: flex-start;
        line-height: 24px;
        label {
          flex: 1;
          color: rgba(4,15,66,.6);
          min-width: 60px;
          display: inline-block;
          text-align: left;
          word-break: break-all;
        }
        .value {
          flex: 3;
          padding-left: 10px;
          word-break: break-all;
          &:hover .icon {
            display: inline-block;
          }
          .pad-r {
            padding-right: 4px;
          }
          .icon {
            color: var(--el-color-primary);
            display: none;
          }
        }
      }
    }
    .right-container {
      flex: 3;
      .tabs {
        display: flex;
        align-items: center;
        font-size: 14px;
        border-bottom: 1px solid rgba(4,15,66,.2);
        &-item {
          cursor: pointer;
          padding: 19px 10px;
          margin-left: 16px;
        }
        .active {
          color: var(--el-color-primary);
          position: relative;
          &::after {
            content: '';
            height: 1px;
            position: absolute;
            bottom: -1px;
            left: 0;
            right: 0;
            background: var(--el-color-primary);
          }
        }
      }
    }
  }
</style>